package com.stars.easyms.gateway.swagger;

import com.stars.easyms.gateway.properties.EasyMsGatewayProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.util.*;

/**
 * <p>className: GatewaySwaggerController</p>
 * <p>description: 网关层swagger的控制层</p>
 *
 * @author guoguifang
 * @version 1.6.3
 * @date 2020/9/12 12:22 上午
 */
@RestController
public class EasyMsGatewaySwaggerController {

    static final String GET_SWAGGER_RESOURCES_URL = "/getSwaggerResources";

    private EasyMsGatewayProperties gatewayProperties;

    private Map<String, Object> resources;

    public EasyMsGatewaySwaggerController(EasyMsGatewayProperties gatewayProperties) {
        this.gatewayProperties = gatewayProperties;
    }

    @GetMapping(EasyMsGatewaySwaggerController.GET_SWAGGER_RESOURCES_URL)
    public Mono<Map<String, Object>> getSwaggerResources() {
        if (gatewayProperties.isDebugEnabled()) {
            return Mono.just(getResources());
        }
        return Mono.empty();
    }

    private Map<String, Object> getResources() {
        if (resources == null) {
            resources = new HashMap<>(4);
            List<Map<String, String>> serviceList = new ArrayList<>();
            gatewayProperties.getService().forEach((key, value) -> {
                Map<String, String> map = new HashMap<>(4);
                map.put("id", key);
                map.put("path", value);
                serviceList.add(map);
            });
            resources.put("resources", serviceList);
            resources.put("servletPath", gatewayProperties.getServletPath());
        }
        return resources;
    }

}
